import router from './router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { getToken } from '@/utils/auth';
import { isHttp } from '@/utils/validate';
import useUserStore from '@/store/modules/user';
import useSettingsStore from '@/store/modules/settings';
import usePermissionStore from '@/store/modules/permission';
import { ElLoading } from 'element-plus';

NProgress.configure({ showSpinner: false });

const whiteList = ['/login'];

let firstPageName = '';
router.beforeEach((to, from, next) => {
  NProgress.start();
  to.meta?.title && useSettingsStore().setTitle(to.meta.title);

  const isLogin = useUserStore().isLogin;

  if (whiteList.includes(to.path)) {
    // 在免登录白名单，直接进入
    next();
  } else if (!getToken()) {
    next(`/login?redirect=${to.fullPath}`); // 重定向到登录页
  } else if (!isLogin) {
    // 判断当前用户是否已拉取完user_info信息
    const loadingInstance = ElLoading.service({ text: '正在拉取用户信息...' });
    useUserStore()
      .getInfo()
      .then(() => {
        usePermissionStore()
          .generateRoutes()
          .then(accessRoutes => {
            // 根据roles权限生成可访问的路由表
            accessRoutes.forEach(route => {
              if (!isHttp(route.path)) router.addRoute(route); // 动态添加可访问路由表
            });
            firstPageName = getFirstPageName(accessRoutes);

            if (to.path !== '/') return next({ ...to, replace: true });

            if (firstPageName) next({ name: firstPageName });
            else next('/no-permiss');
          });
      })
      .finally(() => {
        loadingInstance.close();
      });
  } else if (to.path === '/') {
    if (firstPageName) next({ name: firstPageName });
    else next('/no-permiss');
  } else {
    next();
  }
});

router.afterEach(() => {
  NProgress.done();
});

// 获取有权限的第一个页面
function getFirstPageName(accessRoutes) {
  accessRoutes = accessRoutes || [];
  for (let i = 0; i < accessRoutes.length; i++) {
    const ROUTE_ITEM = accessRoutes[i];
    if (ROUTE_ITEM.hidden) continue;
    if (ROUTE_ITEM?.children?.length) {
      const firsteName = getFirstPageName(ROUTE_ITEM?.children);
      if (firsteName) return firsteName;
    } else {
      return ROUTE_ITEM.name;
    }
  }
}
